package kassiopeia.agent.io.jms;

import javax.jms.MessageListener;
import org.apache.log4j.Logger;
import com.google.common.base.Preconditions;
import kassiopeia.agent.io.ReceiversRegistry;
import kassiopeia.commons.io.Message;
import kassiopeia.commons.util.JmsUtils;

public class JmsMessagePublisher implements MessageListener {

    private static final Logger logger = Logger.getLogger(JmsMessagePublisher.class);

    private ReceiversRegistry receiversRegistry;

    public JmsMessagePublisher(ReceiversRegistry receiversRegistry) {
        Preconditions.checkNotNull(receiversRegistry);
        this.receiversRegistry = receiversRegistry;
    }

    @Override
    public synchronized void onMessage(javax.jms.Message message) {
        logger.debug("Received new JMS message!");

        Message kassiopeiaMessage = JmsUtils.convertObjectMessage(message,Message.class);
        if(kassiopeiaMessage != null) {
            logger.debug("Notifying receivers..");
            receiversRegistry.notifyReceivers(kassiopeiaMessage);
        } else {
            logger.warn("Unknown message type - ignoring mesaage");
        }
    }
}
